import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
import ast


def unpack_ratings(md):
    md.ratings = md.ratings.apply(ast.literal_eval)
    # 添加新的一列
    for i, rate in enumerate(md.ratings):
        maximum = ["", 0]
        for item in rate:
            md.loc[i, item['name'].lower()] = item['count']
            # 添加一列，显示价值最大的评级对象
            if item['count'] > maximum[1]:
                maximum = [item['name'].lower(), item['count']]
        md.loc[i, 'maximum_rating'] = maximum[0]

    # 添加总评分次数计数
    md["rating_count"] = md.ratings.apply(lambda x: get_total_count(x))
    # print(md.head(1))
    return md


def unpack_tags(md):
    md.tags = md.tags.apply(ast.literal_eval)
    return md


def max_rating_count(md):
    md = unpack_ratings(md)
    # distribution of rating
    rating = md["maximum_rating"].value_counts()

    fig = px.pie(names=rating.index, values=rating.values, labels={
        "names": "The rating ",
        "values": "Number of talks "
    },
                 title="The distribution of the maximum rating for each tedtalks",
                 color_discrete_sequence=px.colors.sequential.Bluyl
                 )
    fig.update_layout(
        title_font_color="#fff", paper_bgcolor="#283747", title_font_size=20, title_x=.5, font_color="#bbb",
        plot_bgcolor="#D0D3D4", legend_title_font_size=17, legend_title_font_color="#fff",
        legend_title_text="Occupation")
    fig.update_xaxes(tickfont_size=9)
    fig.update_traces(textfont_size=10)
    fig.show()


def funniest_talks(md):
    md = unpack_ratings(md)
    # funniest talks
    md["funny_ratio"] = round((md["funny"] / md["rating_count"]) * 100, 2)
    funny = md[(md["rating_count"] > md["rating_count"].mean())] \
        .nlargest(10, "funny_ratio").sort_values("funny_ratio", ascending="True")

    fig = px.bar(funny, x="main_speaker", y="funny_ratio", color="speaker_occupation",
                 title="highest 10 tedtakls with Funny_ratings Ratio and their occupation".title(),
                 color_discrete_sequence=px.colors.sequential.Bluyl,
                 hover_data={"name": True},
                 labels={"name": "Talk_name "},
                 text="funny_ratio"
                 )

    fig.update_layout(
        title_font_color="#fff", paper_bgcolor="#283747", title_font_size=20, title_x=.5, font_color="#bbb",
        plot_bgcolor="#D0D3D4 ", legend_title_font_size=17, legend_title_font_color="#fff")
    fig.update_xaxes(tickfont_size=9)
    fig.update_traces(textfont_size=10)
    fig.show()


def most_confusing_talks(md):
    md = unpack_ratings(md)
    # most confusing talks
    md["confuse_ratio"] = round((md["confusing"] / md["rating_count"]) * 100, 2)
    confuse = md[(md["rating_count"] > md["rating_count"].mean())] \
        .nlargest(10, "confuse_ratio").sort_values("confuse_ratio", ascending=True)

    fig = px.bar(confuse, x="main_speaker", y="confuse_ratio", color="speaker_occupation",
                 title="highest 10 tedtakls with confuse_ratio ratings and their occupation",
                 labels={"name": "tedtalk name"},
                 text="confuse_ratio",
                 color_discrete_sequence=px.colors.sequential.Bluyl
                 )
    fig.update_layout(
        title_font_color="#fff", paper_bgcolor="#283747", title_font_size=20, title_x=.5, font_color="#bbb",
        plot_bgcolor="#D0D3D4", legend_title_font_size=17, legend_title_font_color="#fff",
        legend_title_text="Occupation")
    fig.update_xaxes(tickfont_size=9)
    fig.update_traces(textfont_size=10)
    fig.show()


def year_publish_counts(md):
    # 统计每年发布量
    md['year'] = md['published_date'].dt.year
    years = md["year"].value_counts().sort_index(ascending=True)

    fig = px.line(x=years.index, y=years.values,
                  labels={"y": "Number of events", "x": "Year"},
                  title="Number of tedtalks published through years",
                  line_shape="spline",
                  color_discrete_sequence=["#31bf9b"]
                  )
    fig.update_layout(
        title_font_color="#fff", paper_bgcolor="#283747", title_font_size=20, title_x=.5, font_color="#bbb",
        plot_bgcolor="#D0D3D4")
    fig.update_xaxes(tickfont_size=9)
    fig.show()


def views_duration_polar(md):
    # 统计各视频播放量（与时长）
    ten_most_viewed_talks = md.sort_values("views").tail(10)

    fig = px.bar_polar(ten_most_viewed_talks, r="duration", theta="title", color="views",
                       color_discrete_sequence = px.colors.sequential.Bluyl,
                       title = "top 10 talks, number of views and duration"
                 )
    fig.update_layout(
        title_font_color="#fff", paper_bgcolor="#283747", title_font_size=20, title_x=.5, font_color="#bbb",
        plot_bgcolor="#D0D3D4", legend_title_font_size=17, legend_title_font_color="#fff",
        legend_title_text="Occupation")
    fig.show()


def views_comments_scatter(md):
    fig = px.scatter(md, x="comments", y="views", size="comments", color="duration",
                 title="highest 10 tedtakls with views and their occupation",
                 hover_name="title",
                 labels={"name": "tedtalk name"},
                 log_x=True,
                 size_max=80
                 )
    fig.update_layout(
        title_font_color="#fff", paper_bgcolor="#283747", title_font_size=20, title_x=.5, font_color="#bbb",
        plot_bgcolor="#D0D3D4", legend_title_font_size=17, legend_title_font_color="#fff",
        legend_title_text="Occupation")
    fig.update_xaxes(tickfont_size=9)
    fig.update_traces(textfont_size=10)
    fig.show()


def views_occ_bar(md):
    ten_most_viewed_talks = md.sort_values("views").tail(10)

    fig = px.bar(ten_most_viewed_talks, x="title", y="views", color="speaker_occupation",
                 title="highest 10 tedtakls with views and their occupation",
                 labels={"name": "tedtalk name"},
                 text="views",
                 color_discrete_sequence=px.colors.sequential.Bluyl
                 )
    fig.update_layout(
        title_font_color="#fff", paper_bgcolor="#283747", title_font_size=20, title_x=.5, font_color="#bbb",
        plot_bgcolor="#D0D3D4", legend_title_font_size=17, legend_title_font_color="#fff",
        legend_title_text="Occupation")
    fig.update_xaxes(tickfont_size=9)
    fig.update_traces(textfont_size=10)
    fig.show()


def occupations_counts(md):
    # 统计主讲人职业
    occ = md["speaker_occupation"].value_counts().sort_values(ascending=False).nlargest(20)

    fig = px.pie(names=occ.index, values=occ.values, labels={
        "names": "The occupation ",
        "values": "Number of talks "
    },
                 title="The highest 20 occupation with the number of talks",
                 color_discrete_sequence=px.colors.sequential.Bluyl
                 )
    fig.update_layout(
        title_font_color="#fff", paper_bgcolor="#283747", title_font_size=20, title_x=.5, font_color="#bbb",
        plot_bgcolor="#D0D3D4", legend_title_font_size=17, legend_title_font_color="#fff",
        legend_title_text="Occupation")
    fig.update_xaxes(tickfont_size=9)
    fig.update_traces(textfont_size=10)
    fig.show()


def get_total_count(i):
    counts = 0
    for item in i:
        counts += item['count']
    return counts
